﻿using System.ComponentModel;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.Graphics.Gdi;

namespace NetScript2.tools;

class WinTools
{
    public static void printProcessNames()
    {
        PInvoke.EnumWindows((hwnd, param1) =>
        {
            int bufferSize = PInvoke.GetWindowTextLength(hwnd)+1;
            unsafe
            {
                fixed (char* windowNameChars = new char[bufferSize])
                {
                    if (PInvoke.GetWindowText(hwnd, windowNameChars, bufferSize) == 0)
                    {
                        int errorCode = Marshal.GetLastWin32Error();
                        if (errorCode != 0)
                        {
                            throw new Win32Exception(errorCode);
                        }

                        return true;
                    }

                    string windowName = new string(windowNameChars);
                    Console.WriteLine(windowName);
                }

                return true;
            }

            return true;
        }, new LPARAM(0));
    }
    
    public  static void CaptureWindow(HWND hWnd, int width, int height)
    {
        using (var bmp = new Bitmap(width, height))
        {
            using (Graphics memoryGraphics = Graphics.FromImage(bmp))
            {
                IntPtr dc = memoryGraphics.GetHdc();
                HDC hdc = new HDC(dc);
                PInvoke.PrintWindow(hWnd, hdc, 0);
                memoryGraphics.ReleaseHdc(dc);
                string path = ".\\r.png";
                // bmp.Save(path, System.Drawing.Imaging.ImageFormat.Bmp); 
                bmp.Save(path, ImageFormat.Png); 
                // using (MemoryStream ms = new MemoryStream())
                // {
                //     bmp.Save(ms, ImageFormat.Png);
                //     ms.Seek(0, SeekOrigin.Begin);
                //     return ms.ToArray();
                // }
            }
        }
    }
}